$(function () {
    var arr = JSON.parse(localStorage.getItem("bill")) || [];
    console.log(arr);
    var userid = $.cookie("id");
    var $tbody = $("#tbody");
    var $allCount = $("#allCount");
    var $bill = $("#bill");
    var $method = $("#methodlist");
    var count = 0;
    function render() {
        // 根据本地存储中的数据渲染$tbody的内容
        var html = arr.map(value => {
            return `
            <tr>
            <td id="name">
            <a href="./detail.html#${value.slug}" target= "_blank">
            <img id="logo" src="${value.iconUrl}" alt="">
            ${value.title}
            </a>
            </td>
            <td>￥${value.price}</td>
            <td>${value.num}</td>
            <td>￥${value.count}</td>
        </tr>`
        }).join("")
        $tbody.html(html)
    }
    // 定义计算价格函数
    function compute() {
        count = 0;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].isChecked) {
                count += arr[i].count;
            }
        }
        $allCount.html(count);
    }

    render();
    compute();
    $bill.on("click",function(){
        $method = $method.val();
        // 不用arr里的那么多信息，写个bill意思意思
        var bill = [];
        arr.forEach(value => {
            var goods = {"slug":value.slug,"num":value.num,"price":value.price};
            bill.push(goods);
        });
        console.log(bill);
        let isConfirm = confirm("确定提交订单？");
        if(!isConfirm){
            return;
        }
        $.ajax({
            url: "/php/bill.php",
                data: {
                    id: userid,
                    bill,
                    count,
                    method:$method
                },
                type: "post",
                dataType: "json",
                success(data){
                    if (!data.error) {
                        alert(data.data);
                        // 此处应跳转到订单页
                        location.href = "../index.html"; 
                        return;
                    }
                    alert(data.data);
                }
        })
    })
});